#include <vector>

#include "player.h"
#include "debug.h"
#include "unifont.h"

extern Player player;

// -----------------------------
Unifont::Unifont()
// -----------------------------
{
	#include "unifont_seekpoints.c"
}

// -----------------------------
void Unifont::read(std::vector<glyph>* glyphTable)
// -----------------------------
{
	char hexCodeP[5];
	hexCodeP[4] = 0;
	
	std::string line = readFontLine(true);
	bool found = false;
	
	u16 seekPID = 0;
	u32 seekTo;
	bool seek = false;
	
	for (u16 i = 0; i<glyphTable->size(); ++i)
	{
		found = false;
		seek = false;
		
		// covert codepoint from u32 to hex-string
		sprintf( hexCodeP, "%04X", (*glyphTable)[i].codepoint);
		
		while ( (*glyphTable)[i].codepoint >= seekPoint[seekPID].codepoint )
		{
			seekTo = seekPoint[seekPID].byte;
			seek = true;
			++seekPID;
		}
		
		if (seek)
		{
			line = readFontLine(true, seekTo);
		}
		
		// search line by line for the codepoint
		while ( line.size() > 0 )
		{
			
			if (line.compare( 0, 4, hexCodeP ) == 0)
			{
				found = true;
				(*glyphTable)[i].data.assign( line.substr(5, 64) );
				break;
			}
			
			line = readFontLine(false);
		}

		if (!found)
		{
			// reset search from the top for the next codepoint
			line = readFontLine(true);
		}
	}
}

// -----------------------------
std::string Unifont::readFontLine(bool first, long int pos)
// -----------------------------
{
	if (first)
	{
		// open file if not open
		if ( fontFile == NULL ) {
			fontFile = fopen("unifont-jp-5.1.20080820.hex", "r");
		}
		glyphBufferNow = 0;
		// reset the get pointer to 0
		fseek(fontFile, pos, SEEK_SET);
		// read up to 1024 chars
		glyphBufferMax = fread(glyphBuffer, 1, 1024, fontFile);
	}
	
	std::string retLine;
	u16 start = glyphBufferNow;
	bool read = false;
	
	while ( !read )
	{
		++glyphBufferNow;
		
		if ( glyphBufferNow >= glyphBufferMax )
		{
			retLine.append(&glyphBuffer[start], glyphBufferNow - start);
			glyphBufferNow = start = 0;
			glyphBufferMax = fread(glyphBuffer, 1, 1024, fontFile);
		}
		
		if (glyphBuffer[glyphBufferNow] == '\n')
		{
			retLine.append(&glyphBuffer[start], glyphBufferNow - start);
			++glyphBufferNow;
			read = true;
		}

	}
	
	return retLine;
}

